{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:516: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:517: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:518: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:519: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:520: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:525: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:541: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:542: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:543: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:544: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:545: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:550: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n"
     ]
    }
   ],
   "source": [
    "import tensorflow as tf\n",
    "import numpy as np\n",
    "import pickle"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "dict_keys(['train_texts', 'test_texts', 'train_clss', 'test_clss', 'train_labels', 'test_labels'])"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "with open('dataset.pkl', 'rb') as fopen:\n",
    "    dataset = pickle.load(fopen)\n",
    "dataset.keys()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "73967"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(dataset['train_texts'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('dictionary.pkl', 'rb') as fopen:\n",
    "    dictionary = pickle.load(fopen)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "rev_dictionary = dictionary['rev_dictionary']\n",
    "dictionary = dictionary['dictionary']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Model:\n",
    "    def __init__(self, size_layer, num_layers, embedded_size,\n",
    "                 dict_size, learning_rate):\n",
    "        \n",
    "        def cells(reuse=False):\n",
    "            return tf.nn.rnn_cell.LSTMCell(size_layer,initializer=tf.orthogonal_initializer(),reuse=reuse)\n",
    "        \n",
    "        self.X = tf.placeholder(tf.int32, [None, None])\n",
    "        self.Y = tf.placeholder(tf.float32, [None, None])\n",
    "        self.mask = tf.placeholder(tf.int32, [None, None])\n",
    "        self.clss = tf.placeholder(tf.int32, [None, None])\n",
    "        mask = tf.cast(self.mask, tf.float32)\n",
    "        encoder_embeddings = tf.Variable(tf.random_uniform([dict_size, embedded_size], -1, 1))\n",
    "        encoder_embedded = tf.nn.embedding_lookup(encoder_embeddings, self.X)\n",
    "        rnn_cells = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)])\n",
    "        outputs, _ = tf.nn.dynamic_rnn(rnn_cells, encoder_embedded, dtype = tf.float32)\n",
    "        outputs = tf.gather(outputs, self.clss, axis = 1, batch_dims = 1)\n",
    "        self.logits = tf.layers.dense(outputs, 1)\n",
    "        self.logits = tf.squeeze(self.logits, axis=-1)\n",
    "        self.logits = self.logits * mask\n",
    "        crossent = tf.nn.sigmoid_cross_entropy_with_logits(logits=self.logits, labels=self.Y)\n",
    "        crossent = crossent * mask\n",
    "        crossent = tf.reduce_sum(crossent)\n",
    "        total_size = tf.reduce_sum(mask)\n",
    "        self.cost = tf.div_no_nan(crossent, total_size)\n",
    "        \n",
    "        self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n",
    "        \n",
    "        l = tf.round(tf.sigmoid(self.logits))\n",
    "        self.accuracy = tf.reduce_mean(tf.cast(tf.boolean_mask(l, tf.equal(self.Y, 1)), tf.float32))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "size_layer = 256\n",
    "num_layers = 2\n",
    "embedded_size = 256\n",
    "learning_rate = 1e-3\n",
    "batch_size = 128\n",
    "epoch = 20"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From <ipython-input-6-8f447dd98b6a>:6: LSTMCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.LSTMCell, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From <ipython-input-6-8f447dd98b6a>:15: MultiRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.StackedRNNCells, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From <ipython-input-6-8f447dd98b6a>:16: dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `keras.layers.RNN(cell)`, which is equivalent to this API\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/rnn_cell_impl.py:961: calling Zeros.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Call initializer instance with the dtype argument instead of passing it to the constructor\n",
      "WARNING:tensorflow:From <ipython-input-6-8f447dd98b6a>:18: dense (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use keras.layers.dense instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/init_ops.py:1251: calling VarianceScaling.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Call initializer instance with the dtype argument instead of passing it to the constructor\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/nn_impl.py:180: add_dispatch_support.<locals>.wrapper (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use tf.where in 2.0, which has the same broadcast rule as np.where\n"
     ]
    }
   ],
   "source": [
    "tf.reset_default_graph()\n",
    "sess = tf.InteractiveSession()\n",
    "model = Model(size_layer,num_layers,embedded_size,len(dictionary),learning_rate)\n",
    "sess.run(tf.global_variables_initializer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "UNK = 3\n",
    "\n",
    "def str_idx(corpus, dic):\n",
    "    X = []\n",
    "    for i in corpus:\n",
    "        ints = []\n",
    "        for k in i.split():\n",
    "            ints.append(dic.get(k,UNK))\n",
    "        X.append(ints)\n",
    "    return X\n",
    "\n",
    "def pad_sentence_batch(sentence_batch, pad_int):\n",
    "    padded_seqs = []\n",
    "    seq_lens = []\n",
    "    max_sentence_len = max([len(sentence) for sentence in sentence_batch])\n",
    "    for sentence in sentence_batch:\n",
    "        padded_seqs.append(sentence + [pad_int] * (max_sentence_len - len(sentence)))\n",
    "        seq_lens.append(len(sentence))\n",
    "    return padded_seqs, seq_lens"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_X = str_idx(dataset['train_texts'], dictionary)\n",
    "test_X = str_idx(dataset['test_texts'], dictionary)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_clss = dataset['train_clss']\n",
    "test_clss = dataset['test_clss']\n",
    "train_Y = dataset['train_labels']\n",
    "test_Y = dataset['test_labels']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(0.27272728, 0.68941796)"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "batch_x, _ = pad_sentence_batch(train_X[:5], 0)\n",
    "batch_y, _ = pad_sentence_batch(train_Y[:5], 0)\n",
    "batch_clss, _ = pad_sentence_batch(train_clss[:5], -1)\n",
    "batch_clss = np.array(batch_clss)\n",
    "batch_mask = 1 - (batch_clss == -1)\n",
    "batch_clss[batch_clss == -1] = 0\n",
    "\n",
    "feed = {model.X: batch_x,\n",
    "        model.Y: batch_y,\n",
    "        model.mask: batch_mask,\n",
    "        model.clss: batch_clss}\n",
    "acc, loss, _ = sess.run([model.accuracy, model.cost,model.optimizer], feed_dict = feed)\n",
    "acc, loss"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 578/578 [23:49<00:00,  2.47s/it, accuracy=0, cost=0.267]      \n",
      "minibatch loop: 100%|██████████| 145/145 [02:01<00:00,  1.19it/s, accuracy=0, cost=0.221]\n",
      "minibatch loop:   0%|          | 0/578 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, training avg loss 0.262667, training avg acc 0.000085\n",
      "epoch 1, testing avg loss 0.252563, testing avg acc 0.000000\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 578/578 [23:49<00:00,  2.47s/it, accuracy=0, cost=0.264]\n",
      "minibatch loop: 100%|██████████| 145/145 [02:00<00:00,  1.20it/s, accuracy=0, cost=0.221]\n",
      "minibatch loop:   0%|          | 0/578 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 2, training avg loss 0.252687, training avg acc 0.000000\n",
      "epoch 2, testing avg loss 0.250887, testing avg acc 0.000000\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 578/578 [23:49<00:00,  2.47s/it, accuracy=0.0106, cost=0.261] \n",
      "minibatch loop: 100%|██████████| 145/145 [02:01<00:00,  1.19it/s, accuracy=0, cost=0.219]      \n",
      "minibatch loop:   0%|          | 0/578 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 3, training avg loss 0.249986, training avg acc 0.000347\n",
      "epoch 3, testing avg loss 0.250423, testing avg acc 0.000835\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 578/578 [23:48<00:00,  2.47s/it, accuracy=0.0177, cost=0.254] \n",
      "minibatch loop: 100%|██████████| 145/145 [02:01<00:00,  1.19it/s, accuracy=0.0129, cost=0.221] \n",
      "minibatch loop:   0%|          | 0/578 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 4, training avg loss 0.245642, training avg acc 0.005859\n",
      "epoch 4, testing avg loss 0.253216, testing avg acc 0.006405\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 578/578 [23:48<00:00,  2.47s/it, accuracy=0.0532, cost=0.243] \n",
      "minibatch loop: 100%|██████████| 145/145 [02:01<00:00,  1.19it/s, accuracy=0.0452, cost=0.228] \n",
      "minibatch loop:   0%|          | 0/578 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 5, training avg loss 0.238232, training avg acc 0.026460\n",
      "epoch 5, testing avg loss 0.260064, testing avg acc 0.025689\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 578/578 [23:48<00:00,  2.47s/it, accuracy=0.0922, cost=0.231]\n",
      "minibatch loop: 100%|██████████| 145/145 [02:01<00:00,  1.20it/s, accuracy=0.0516, cost=0.235]\n",
      "minibatch loop:   0%|          | 0/578 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 6, training avg loss 0.228040, training avg acc 0.069235\n",
      "epoch 6, testing avg loss 0.269286, testing avg acc 0.036230\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 578/578 [23:47<00:00,  2.47s/it, accuracy=0.17, cost=0.216]  \n",
      "minibatch loop: 100%|██████████| 145/145 [02:01<00:00,  1.19it/s, accuracy=0.0516, cost=0.24] \n",
      "minibatch loop:   0%|          | 0/578 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 7, training avg loss 0.215618, training avg acc 0.125084\n",
      "epoch 7, testing avg loss 0.272501, testing avg acc 0.045919\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 578/578 [23:48<00:00,  2.47s/it, accuracy=0.238, cost=0.203] \n",
      "minibatch loop: 100%|██████████| 145/145 [02:01<00:00,  1.20it/s, accuracy=0.0839, cost=0.257]\n",
      "minibatch loop:   0%|          | 0/578 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 8, training avg loss 0.201337, training avg acc 0.187912\n",
      "epoch 8, testing avg loss 0.287809, testing avg acc 0.070733\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 578/578 [23:47<00:00,  2.47s/it, accuracy=0.312, cost=0.186]\n",
      "minibatch loop: 100%|██████████| 145/145 [02:00<00:00,  1.20it/s, accuracy=0.103, cost=0.281] \n",
      "minibatch loop:   0%|          | 0/578 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 9, training avg loss 0.186864, training avg acc 0.249759\n",
      "epoch 9, testing avg loss 0.315843, testing avg acc 0.084132\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 578/578 [23:46<00:00,  2.47s/it, accuracy=0.358, cost=0.169]\n",
      "minibatch loop: 100%|██████████| 145/145 [02:01<00:00,  1.20it/s, accuracy=0.11, cost=0.314]  \n",
      "minibatch loop:   0%|          | 0/578 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 10, training avg loss 0.172965, training avg acc 0.309004\n",
      "epoch 10, testing avg loss 0.339780, testing avg acc 0.092134\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 578/578 [23:51<00:00,  2.48s/it, accuracy=0.443, cost=0.153]\n",
      "minibatch loop: 100%|██████████| 145/145 [02:00<00:00,  1.20it/s, accuracy=0.135, cost=0.348] \n",
      "minibatch loop:   0%|          | 0/578 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 11, training avg loss 0.159476, training avg acc 0.365974\n",
      "epoch 11, testing avg loss 0.374555, testing avg acc 0.111304\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 578/578 [23:49<00:00,  2.47s/it, accuracy=0.482, cost=0.132]\n",
      "minibatch loop: 100%|██████████| 145/145 [02:01<00:00,  1.20it/s, accuracy=0.129, cost=0.357] \n",
      "minibatch loop:   0%|          | 0/578 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 12, training avg loss 0.145508, training avg acc 0.424775\n",
      "epoch 12, testing avg loss 0.380014, testing avg acc 0.103223\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 578/578 [23:49<00:00,  2.47s/it, accuracy=0.479, cost=0.123]\n",
      "minibatch loop: 100%|██████████| 145/145 [02:01<00:00,  1.20it/s, accuracy=0.123, cost=0.357] \n",
      "minibatch loop:   0%|          | 0/578 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 13, training avg loss 0.132634, training avg acc 0.476701\n",
      "epoch 13, testing avg loss 0.392311, testing avg acc 0.098482\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 578/578 [23:49<00:00,  2.47s/it, accuracy=0.475, cost=0.12]  \n",
      "minibatch loop: 100%|██████████| 145/145 [02:01<00:00,  1.20it/s, accuracy=0.11, cost=0.357]  \n",
      "minibatch loop:   0%|          | 0/578 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 14, training avg loss 0.121177, training avg acc 0.523573\n",
      "epoch 14, testing avg loss 0.401181, testing avg acc 0.082353\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 578/578 [23:43<00:00,  2.46s/it, accuracy=0.585, cost=0.105] \n",
      "minibatch loop: 100%|██████████| 145/145 [02:00<00:00,  1.20it/s, accuracy=0.148, cost=0.416] \n",
      "minibatch loop:   0%|          | 0/578 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 15, training avg loss 0.110205, training avg acc 0.566239\n",
      "epoch 15, testing avg loss 0.457439, testing avg acc 0.102568\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 578/578 [23:41<00:00,  2.46s/it, accuracy=0.617, cost=0.0902]\n",
      "minibatch loop: 100%|██████████| 145/145 [02:01<00:00,  1.20it/s, accuracy=0.142, cost=0.442] \n",
      "minibatch loop:   0%|          | 0/578 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 16, training avg loss 0.098867, training avg acc 0.610249\n",
      "epoch 16, testing avg loss 0.508520, testing avg acc 0.109937\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 578/578 [23:44<00:00,  2.46s/it, accuracy=0.66, cost=0.0792] \n",
      "minibatch loop: 100%|██████████| 145/145 [02:01<00:00,  1.19it/s, accuracy=0.129, cost=0.441] \n",
      "minibatch loop:   0%|          | 0/578 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 17, training avg loss 0.089521, training avg acc 0.646151\n",
      "epoch 17, testing avg loss 0.516304, testing avg acc 0.108609\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 578/578 [23:42<00:00,  2.46s/it, accuracy=0.73, cost=0.0708] \n",
      "minibatch loop: 100%|██████████| 145/145 [02:00<00:00,  1.20it/s, accuracy=0.168, cost=0.48]  \n",
      "minibatch loop:   0%|          | 0/578 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 18, training avg loss 0.081986, training avg acc 0.674612\n",
      "epoch 18, testing avg loss 0.546543, testing avg acc 0.129065\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 578/578 [23:40<00:00,  2.46s/it, accuracy=0.745, cost=0.0597]\n",
      "minibatch loop: 100%|██████████| 145/145 [02:00<00:00,  1.20it/s, accuracy=0.148, cost=0.478] \n",
      "minibatch loop:   0%|          | 0/578 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 19, training avg loss 0.074648, training avg acc 0.702221\n",
      "epoch 19, testing avg loss 0.547588, testing avg acc 0.135218\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 578/578 [23:43<00:00,  2.46s/it, accuracy=0.716, cost=0.0659]\n",
      "minibatch loop: 100%|██████████| 145/145 [02:01<00:00,  1.19it/s, accuracy=0.174, cost=0.512] "
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 20, training avg loss 0.068429, training avg acc 0.724982\n",
      "epoch 20, testing avg loss 0.577269, testing avg acc 0.130517\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "import tqdm\n",
    "\n",
    "for e in range(epoch):\n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(train_X), batch_size), desc = 'minibatch loop')\n",
    "    train_loss, train_acc, test_loss, test_acc = [], [], [], []\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(train_X))\n",
    "        batch_x, _ = pad_sentence_batch(train_X[i : index], 0)\n",
    "        batch_y, _ = pad_sentence_batch(train_Y[i : index], 0)\n",
    "        batch_clss, _ = pad_sentence_batch(train_clss[i : index], -1)\n",
    "        batch_clss = np.array(batch_clss)\n",
    "        batch_mask = 1 - (batch_clss == -1)\n",
    "        batch_clss[batch_clss == -1] = 0\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y,\n",
    "                model.mask: batch_mask,\n",
    "                model.clss: batch_clss}\n",
    "        accuracy, loss, _ = sess.run([model.accuracy,model.cost,model.optimizer],\n",
    "                                    feed_dict = feed)\n",
    "        train_loss.append(loss)\n",
    "        train_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(test_X), batch_size), desc = 'minibatch loop')\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(test_X))\n",
    "        batch_x, _ = pad_sentence_batch(test_X[i : index], 0)\n",
    "        batch_y, _ = pad_sentence_batch(test_Y[i : index], 0)\n",
    "        batch_clss, _ = pad_sentence_batch(test_clss[i : index], -1)\n",
    "        batch_clss = np.array(batch_clss)\n",
    "        batch_mask = 1 - (batch_clss == -1)\n",
    "        batch_clss[batch_clss == -1] = 0\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y,\n",
    "                model.mask: batch_mask,\n",
    "                model.clss: batch_clss}\n",
    "        accuracy, loss = sess.run([model.accuracy,model.cost],\n",
    "                                    feed_dict = feed)\n",
    "\n",
    "        test_loss.append(loss)\n",
    "        test_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    print('epoch %d, training avg loss %f, training avg acc %f'%(e+1,\n",
    "                                                                 np.mean(train_loss),np.mean(train_acc)))\n",
    "    print('epoch %d, testing avg loss %f, testing avg acc %f'%(e+1,\n",
    "                                                              np.mean(test_loss),np.mean(test_acc)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import rouge\n",
    "from tensorflow.keras.preprocessing import sequence\n",
    "\n",
    "def calculate_rouges(predicted, batch_y):\n",
    "    non = np.count_nonzero(batch_y, axis = 1)\n",
    "    o = []\n",
    "    for n in non:\n",
    "        o.append([True for _ in range(n)])\n",
    "    b = sequence.pad_sequences(o, dtype = np.bool, padding = 'post', value = False)\n",
    "    batch_y = np.array(batch_y)\n",
    "    rouges = []\n",
    "    for i in range(predicted.shape[0]):\n",
    "        a = batch_y[i][b[i]]\n",
    "        p = predicted[i][b[i]]\n",
    "        rouges.append(rouge.rouge_n([p], [a]))\n",
    "    return np.mean(rouges)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "metadata": {},
   "outputs": [],
   "source": [
    "batch_x, _ = pad_sentence_batch(test_X[: 5], 0)\n",
    "batch_y, _ = pad_sentence_batch(test_Y[: 5], 0)\n",
    "batch_clss, _ = pad_sentence_batch(test_clss[: 5], -1)\n",
    "batch_clss = np.array(batch_clss)\n",
    "batch_y = np.array(batch_y)\n",
    "batch_x = np.array(batch_x)\n",
    "cp_batch_clss = batch_clss.copy()\n",
    "batch_mask = 1 - (batch_clss == -1)\n",
    "batch_clss[batch_clss == -1] = 0\n",
    "\n",
    "feed = {model.X: batch_x,\n",
    "        model.mask: batch_mask,\n",
    "        model.clss: batch_clss}\n",
    "predicted = sess.run(tf.round(tf.sigmoid(model.logits)), feed_dict = feed)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.20137092"
      ]
     },
     "execution_count": 59,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from tensor2tensor.utils import rouge\n",
    "\n",
    "def calculate_rouge(predicted, batch_y, cp_batch_clss, batch_x):\n",
    "    f, y_, predicted_ = [], [], []\n",
    "    for i in range(len(cp_batch_clss)):\n",
    "        f.append(cp_batch_clss[i][cp_batch_clss[i] != -1])\n",
    "        y_.append(batch_y[i][cp_batch_clss[i] != -1])\n",
    "        predicted_.append(predicted[i][cp_batch_clss[i] != -1])\n",
    "    \n",
    "    actual, predict = [], []\n",
    "    for i in range(len(f)):\n",
    "        actual_, predict_ = [], []\n",
    "        for k in range(len(f[i])):\n",
    "            if k == (len(f[i]) - 1):\n",
    "                s = batch_x[i][f[i][k]:]\n",
    "                s = s[s != 0]\n",
    "            else:\n",
    "                s = batch_x[i][f[i][k]: f[i][k + 1]]\n",
    "            s = [w for w in s if w not in [0, 1, 2, 3, 5, 6, 7, 8]]\n",
    "            if y_[i][k]:\n",
    "                actual_.extend(s)\n",
    "            if predicted_[i][k]:\n",
    "                predict_.extend(s)\n",
    "        actual.append(actual_)\n",
    "        predict.append(predict_)\n",
    "    return rouge.rouge_n(predict, actual)\n",
    "\n",
    "calculate_rouge(predicted, batch_y, cp_batch_clss, batch_x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tqdm import tqdm as tqdm_base\n",
    "def tqdm(*args, **kwargs):\n",
    "    if hasattr(tqdm_base, '_instances'):\n",
    "        for instance in list(tqdm_base._instances):\n",
    "            tqdm_base._decr_instances(instance)\n",
    "    return tqdm_base(*args, **kwargs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n",
      "minibatch loop:   0%|          | 1/578 [03:28<33:22:59, 208.28s/it, rouge=0.184]\n",
      "minibatch loop:   2%|▏         | 13/578 [03:01<2:11:19, 13.95s/it, rouge=0.181]\n",
      "minibatch loop: 100%|██████████| 578/578 [10:19<00:00,  1.07s/it, rouge=0.155]\n"
     ]
    }
   ],
   "source": [
    "rouges = []\n",
    "\n",
    "pbar = tqdm(\n",
    "    range(0, len(test_X), 32), desc = 'minibatch loop')\n",
    "for i in pbar:\n",
    "    index = min(i + batch_size, len(test_X))\n",
    "    batch_x, _ = pad_sentence_batch(test_X[i: index], 0)\n",
    "    batch_y, _ = pad_sentence_batch(test_Y[i: index], 0)\n",
    "    batch_clss, _ = pad_sentence_batch(test_clss[i: index], -1)\n",
    "    batch_clss = np.array(batch_clss)\n",
    "    batch_y = np.array(batch_y)\n",
    "    batch_x = np.array(batch_x)\n",
    "    cp_batch_clss = batch_clss.copy()\n",
    "    batch_mask = 1 - (batch_clss == -1)\n",
    "    batch_clss[batch_clss == -1] = 0\n",
    "\n",
    "    feed = {model.X: batch_x,\n",
    "            model.mask: batch_mask,\n",
    "            model.clss: batch_clss}\n",
    "    predicted = sess.run(tf.round(tf.sigmoid(model.logits)), feed_dict = feed)\n",
    "    rouge_ = calculate_rouge(predicted, batch_y, cp_batch_clss, batch_x)\n",
    "    rouges.append(rouge_)\n",
    "    pbar.set_postfix(rouge = rouge_)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.1613218"
      ]
     },
     "execution_count": 64,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.mean(rouges)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
